import requests
import json
import pymongo
import urllib

# 酷狗 API 接口说明
# srs = 'https://blog.csdn.net/mingwang20/article/details/73556796

client = pymongo.MongoClient()
db = client.music
db_songs = db.songs

headers = {
    'User-Agent': 'Chrome',
    'Referer':'http://www.kugou.com'
}

# 搜索关键词，将歌曲存入数据库
def search(keyword):
    url = 'http://songsearch.kugou.com/song_search_v2?keyword=%s&page=1&pagesize=50' % urllib.parse.quote(keyword)
    req = requests.get(url, headers=headers)
    content = req.json()
    for item in content['data']['lists']:
        db_songs.insert_one(item)

# 获取歌词
def get_lyric():
    url_s = 'http://www.kugou.com/yy/index.php?r=play/getdata&hash='
    # 遍历所有歌曲
    for song in db_songs.find():
        hash_str = song['FileHash']
        req = requests.get(url_s + hash_str, headers=headers)
        content = req.json()
        print(content)
        # 使用 update_one 防止重复信息
        db_songs.update_one({'FileHash': hash_str}, {'$set': {'lyrics': content['data']['lyrics']}}, upsert=True)


search('爱')
get_lyric()